package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {


    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 添加购物车方法
     *
     * @param shoppingCart 前端传递过来的购物车数据
     * @return ShoppingCart   返回添加成功后的购物车数据
     */
    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        //1.判断当前加入的菜品或套餐在当前用户的购物车数据记录中是否含有这个数据
        ShoppingCart byShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
        if (byShoppingCart != null) {
            //2.如果有,数量加1,调用mapper更新数据
            byShoppingCart.setNumber(byShoppingCart.getNumber()+1);
            shoppingCartMapper.updateNumber(byShoppingCart.getId(),byShoppingCart.getNumber());
        } else {
            //3.如果没有,调用mapper新增一条购物车记录数据
            byShoppingCart = shoppingCart;
            byShoppingCart.setCreateTime(LocalDateTime.now());

            //完善数据
            byShoppingCart.setNumber(1);


            //新增插入
            shoppingCartMapper.save(byShoppingCart);
        }
        //4.返回最新的购物车数据
        return byShoppingCart;
    }

    @Override
    public ShoppingCart subCart(ShoppingCart shoppingCart) {
        //1.判断当前加入的菜品或套餐在当前用户的购物车数据记录中是否含有这个数据
        ShoppingCart byShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
        if (byShoppingCart != null && byShoppingCart.getNumber()>0 ) {
            //2.如果有,数量加1,调用mapper更新数据
            byShoppingCart.setNumber(byShoppingCart.getNumber()-1);
            shoppingCartMapper.updateNumber(byShoppingCart.getId(),byShoppingCart.getNumber());
        } else {
            //3.如果没有,调用mapper新增一条购物车记录数据
            byShoppingCart = shoppingCart;
            byShoppingCart.setCreateTime(LocalDateTime.now());

            //完善数据
            byShoppingCart.setNumber(1);


            //新增插入
            shoppingCartMapper.save(byShoppingCart);
        }
        //4.返回最新的购物车数据
        return byShoppingCart;
    }

    /**
     * 查询指定用户的购物车集合数据
     *
     * @param userId 用户id
     * @return List 返回购物车集合数据
     */
    @Override
    public List<ShoppingCart> findAllByUserId(Long userId) {
        return shoppingCartMapper.findAllByUserId(userId) ;
    }

    /**
     * 删除指定用户的购物车集合数据
     *
     * @param userId
     * @return
     */
    @Override
    public void clean(Long userId) {
        shoppingCartMapper.deleteByUserId(userId);

    }


}
